﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.AdminCP.Common;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


namespace LinkCard.AdminCP.MktSupplier
{
    public partial class supplier_all_published : System.Web.UI.Page
    {
        public string sName = "";
        public string sAddress = "";
        public string sPhone = "";
        public string sTaxCode = "";
        public string sEmail = "";
        public string sContactPersonName = "";

        private int _totalRecords;
        private int nPageSize = 20;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null) { Response.Redirect("/login.aspx"); }
            else
            {
                if (hash1way.CheckPermission(hash1way.GetPermission(Session["USER"].ToString()), "SYSADMIN") == false)
                {
                    if (hash1way.CheckPermission(hash1way.GetPermission(Session["USER"].ToString()), "SUPPLIER") == false)
                    {
                        Response.Redirect("/message_box.aspx?why=1&msg=5");
                    }
                }
            }

            if (!Page.IsPostBack)
            {
                if (Request.QueryString["Name"] != null) { sName = Request.QueryString["Name"].Trim(); }
                if (Request.QueryString["Address"] != null) { sAddress = Request.QueryString["Address"].Trim(); }
                if (Request.QueryString["Phone"] != null) { sPhone = Request.QueryString["Phone"].Trim(); }
                if (Request.QueryString["TaxCode"] != null) { sTaxCode = Request.QueryString["TaxCode"].Trim(); }
                if (Request.QueryString["Email"] != null) { sEmail = Request.QueryString["Email"].Trim(); }
                if (Request.QueryString["ContactPersonName"] != null) { sContactPersonName = Request.QueryString["ContactPersonName"].Trim(); }


                DataBindPaging();
            }

        }

        protected Int64 getUserID()
        {

            DataTable dt = LinkCard.Utils.DataHelper.SelectTable("SELECT UserID FROM [User] WHERE Username ='" + Session["USER"].ToString() + "'", false);
            if (dt.Rows.Count > 0)
            {
                return ConvertUtility.ToInt64(dt.Rows[0]["UserID"]);
            }
            else
            {
                return 0;
            }
        }

        private void DataBindPaging()
        {

            try
            {
                string sFilter = "AND ([Status] = 2 or [Status] = -1) ";
                if (sName != "" && sName != "Tên công ty") sFilter = sFilter + " AND [Name] like N'%" + sName + "%'";

                if (sAddress != "" && sAddress != "Địa chỉ") sFilter = sFilter + " AND Address like N'" + sAddress + "'";

                if (sPhone != "" && sPhone != "Số điện thoại") sFilter = sFilter + " AND Phone = '" + sPhone +"'";

                if (sTaxCode != "" && sTaxCode != "Mã số thuế") sFilter = sFilter + " AND TaxCode = '" + sTaxCode + "'";

                if (sEmail != "" && sEmail != "Email") sFilter = sFilter + " AND Email = '" + sEmail + "'";

                if (sContactPersonName != "" && sEmail != "Email") sFilter = sFilter + " AND ContactPersonName = N'" + sContactPersonName + "'";


                int curpage = 0;

                if (Request.QueryString["page"] != null)
                {
                    curpage = Convert.ToInt32(Request.QueryString["page"]);
                }
                else
                {
                    curpage = 1;
                }
                
                

                DataTable dt = LinkCard.Utils.DataHelper.LoadPageInSQL("SupplierList", curpage, nPageSize, ref _totalRecords, new SqlParameter("@Filter", sFilter));

                if (dt.Rows.Count > 0)
                {
                    int nPageCount;

                    if (_totalRecords % nPageSize == 0)
                    {
                        nPageCount = _totalRecords / nPageSize;
                    }
                    else {
                        nPageCount = Convert.ToInt32(_totalRecords / nPageSize) + 1;
                    }
                    
                    if (nPageCount < 2) divPager.Visible = false;
                    
                    PagerShow.Text = LinkCard.Utils.hash1way.ShowPageNavigation(curpage, nPageCount);
                    
                    msgList.DataSource = dt;
                    
                    msgList.DataBind();
                    msgNoData.Visible = false;

                }
                
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void msgList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;
            DataRowView row = (DataRowView)e.Item.DataItem;

            var chkDelete = (HtmlInputCheckBox)e.Item.FindControl("chkDelete");
            chkDelete.Value = row["SupplierID"].ToString();

            //var iOrder = (HtmlInputText)e.Item.FindControl("txtOrder");
            //iOrder.Value = row["SupplierOrder"].ToString();


            var imgStatus = (HtmlImage)e.Item.FindControl("SupplierStatus");

            if (row["Status"].ToString() == "-1")
            {
                imgStatus.Src = "../Template/images/icons/trash.gif";
                imgStatus.Alt = "Đã xóa";
            }
            else
            {
                imgStatus.Alt = "Đang hoạt động";
                imgStatus.Src = "../Template/images/icons/tick.png";
            }


        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int nAction = int.Parse(ActionOption.Value);
            if (nAction == 1)
            {
                string sArray = "(0";

                foreach (RepeaterItem item in msgList.Items)
                {
                    var chkDelete = (HtmlInputCheckBox)item.FindControl("chkDelete");
                    if (chkDelete.Checked)
                    {
                        sArray = sArray + "," + chkDelete.Value + "";
                        //Lưu log. Mỗi đối tác lưu 1 bản ghi
                        var logAction = LinkCard.Utils.LogActions.LogItem(getUserID(), Convert.ToInt64(chkDelete.Value), 0, 0, 0, "Xóa Đối tác", "DeleteSupplier", "AdminCP - Supplier");
                    }
                }
                sArray = sArray + ")";

                string sSQL = "update Supplier set Status=-1 where SupplierID in" + sArray;
                LinkCard.Utils.DataHelper.ExecuteNonQuery(sSQL, true);

                string sSQLDeleteStaff = "update ShopStaff set Status =-1 where SupplierID in" + sArray;
                LinkCard.Utils.DataHelper.ExecuteNonQuery(sSQLDeleteStaff, true);

                Response.Redirect("/Supplier/supplier_all_published.aspx");
            }
            if (nAction == 2)
            {
                string sArray = "(0";

                foreach (RepeaterItem item in msgList.Items)
                {
                    var chkDelete = (HtmlInputCheckBox)item.FindControl("chkDelete");
                    if (chkDelete.Checked)
                    {
                        sArray = sArray + "," + chkDelete.Value + "";
                        //Lưu log. Mỗi đối tác lưu 1 bản ghi
                        var logAction = LinkCard.Utils.LogActions.LogItem(getUserID(), Convert.ToInt64(chkDelete.Value), 0, 0, 0, "Khôi phục Đối tác", "RestoreSupplier", "AdminCP - Supplier");
                    }
                }
                sArray = sArray + ")";

                string sSQL = "update Supplier set Status=2 where SupplierID in" + sArray;
                LinkCard.Utils.DataHelper.ExecuteNonQuery(sSQL, true);

                string sSQLDeleteStaff = "update ShopStaff set Status =1 where SupplierID in" + sArray;
                LinkCard.Utils.DataHelper.ExecuteNonQuery(sSQLDeleteStaff, true);

                Response.Redirect("/Supplier/supplier_all_published.aspx");
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

            sName = Name.Value.Trim();
            sAddress = Address.Value.Trim();
            sTaxCode = TaxCode.Value.Trim();
            sEmail = Email.Value.Trim();
            sPhone = Phone.Value.Trim();
            sContactPersonName = ContactPersonName.Value.Trim();
            DataBindPaging();

        }

    }
}